/*
 * 程序入口模块
 *
 * 负责启动所有组件，设置守护进程模式
 *
 **/

#include <unistd.h>
#include "hot.hh"
#include "business.hh"
#include "server.hh"

namespace cloud
{

class entry
{
public:
    entry()
        : _hot(hot_manager::instance())
        , _svr(server::instance())
    {}

    entry& regist()
    {
        _svr.regist(business::search,
                    business::record,
                    business::upload,
                    business::download,
                    business::filelist,
                    business::webserver);
        return *this;
    }

    entry& run()
    {
        _hot.run();
        _svr.run();
        return *this;
    }

    static void daemonize()
    {
        int id = fork();

        if (id < 0)
            easylog::fatal("daemonize fork failed");
        else if (id > 0)
            exit(0);

        if (setsid() < 0)
            easylog::fatal("daemonize setsid failed");

        umask(00);

        // if (chdir("/") < 0)
        //     easylog::fatal("daemonize chdir failed");

        close(0);
        close(1);
        close(2);
    }

    static void set_logger()
    {
        easylog::logger_builder::ptr llb =
            std::make_shared<easylog::local_logger_builder>();
        llb->build_logger_name("default");
        llb->build_logger_type(easylog::logger_type::async);
        llb->build_limit_level(easylog::level_enum::info);
        llb->build_sinker<easylog::file_sinker>();
        llb->build_work_type(easylog::worker_type::safe);
        llb->build_thread_num(1);
        llb->build_buffer_size();
        llb->build_buffer_increment();
        llb->build_buffer_threshold();
        easylog::logger::ptr lgr = llb->build();
        lgr->set_always_flush(true);
        easylog::add(lgr);
    }

private:
    hot_manager& _hot;
    server& _svr;
};

}

int main()
{
    cloud::entry::daemonize();
    cloud::entry::set_logger();
    easylog::info("server process daemonized");
    cloud::entry().regist().run();

    return 0;
}
